package com.example.cardgame

import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.example.cardgame.databinding.ActivityMainBinding
import com.example.cardgame.model.CardMatchingGame

var game: CardMatchingGame = CardMatchingGame(24)

class MainActivity:ComponentActivity() {
    private  val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    var highestscore = 0;

    lateinit var adapter: CardAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val intent = getIntent()
        val currentscore = intent.getStringExtra(SCORE_MSG)?.toInt()


        adapter = CardAdapter(game)
        binding.recyclerView.adapter = adapter


        val configure = resources.configuration
        if (configure.orientation == Configuration.ORIENTATION_PORTRAIT) {
            binding.recyclerView.layoutManager = GridLayoutManager(this,4)
        }else{
            binding.recyclerView.layoutManager = GridLayoutManager(this,6)
        }


        adapter.setOnClickListener {
            game.chooseCardAtIndex(it)
            updateUI()
        }

        updateUI()

        binding.reset.setOnClickListener{
            if (highestscore<game.score) {highestscore = game.score};
            game.reset()
            updateUI()
        }

        binding.retrn.setOnClickListener{
            val intent = Intent()
            if (game.score>highestscore) {highestscore=game.score}
            if (currentscore != null&& currentscore < highestscore) {
                    intent.putExtra(SCORE_MSG,highestscore.toString())
                    setResult(2,intent)
            }
            finish()
        }
    }

    fun updateUI(){
        adapter.notifyDataSetChanged()
        binding.scores.text = String.format("%s%d",getString(R.string.scores),game.score)
    }

}